package com.UnionPayCenter.controller;

import com.UnionPayCenter.entity.ManagerEntity;
import com.UnionPayCenter.entity.ResponseWrapper;
import com.UnionPayCenter.entity.UserEntity;
import com.UnionPayCenter.entity.vo.UserVo;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.jwt.CurrentManager;
import com.UnionPayCenter.jwt.CurrentShop;
import com.UnionPayCenter.jwt.RedisTokenManager;
import com.UnionPayCenter.jwt.TokenEntity;
import com.UnionPayCenter.service.IUserService;
import com.UnionPayCenter.sms.StringUtil;
import com.UnionPayCenter.swagger.ApiJsonObject;
import com.UnionPayCenter.swagger.ApiJsonProperty;
import com.UnionPayCenter.user.dto.WechatCodeQueryDTO;
import com.UnionPayCenter.user.dto.WechatRegisterDTO;
import com.UnionPayCenter.user.service.UserOperatorService;
import com.UnionPayCenter.user.service.UserQueryService;
import com.UnionPayCenter.user.vo.WechatOpenIdExistsVO;
import com.UnionPayCenter.util.AES;
import com.UnionPayCenter.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @program: UnionPayCenter
 * @description: 会员
 * @author: bite
 * @create:
 **/
@Slf4j
@Api(value = "user", tags = "会员")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTokenManager tokenManager;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private UserOperatorService userOperatorService;

    @RequestMapping(value = "/getVerificationCode", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端]会员获取验证码", response = String.class)
    public ResponseWrapper getVerificationCode(
            @ApiJsonObject(name = "userGetVerificationCodeParams", value = {
                    @ApiJsonProperty(key = "mobile", value = "手机号"),
                    @ApiJsonProperty(key = "type", value = "0-注册 1-支付验证", type = "int", required = false)
            }) @RequestBody JSONObject jsonParam) {
        try {
            String mobile = jsonParam.getString("mobile");
            if (mobile == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "手机号码"));
            }
            userService.getVerificationCode(jsonParam);
            return ResponseWrapper.succeed("发送成功");
        }catch (ApiException e){
            log.error(String.format("[前端]会员获取验证码失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[前端]会员获取验证码失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @RequestMapping(value = "/registry", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端]会员注册/登录", response = UserEntity.class)
    public ResponseWrapper registry(
            @ApiJsonObject(name = "userRegistryParams", value = {
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "mobile", value = "手机号"),
                    @ApiJsonProperty(key = "code", value = "验证码"),
                    @ApiJsonProperty(key = "parentId", value = "分销人id" ,required = false)
            })@RequestBody JSONObject jsonParam) {
        try {
            String mobile = jsonParam.getString("mobile");
            if (StringUtils.isNullStr(mobile)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "手机号"));
            }
            String code = jsonParam.getString("code");
            if (StringUtils.isNullStr(code)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "验证码"));
            }

            UserVo user = userService.registry(jsonParam);
            return ResponseWrapper.succeed(user);
        }catch (ApiException e){
            log.error(String.format("[前端]会员注册/登录失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[前端]会员注册/登录失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @RequestMapping(value = "/getUser", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端]获取会员信息", response = UserEntity.class)
    public ResponseWrapper getUser(
            @ApiJsonObject(name = "userGetUserParams", value = {
                    @ApiJsonProperty(key = "userId", value = "会员id", type = "int")
            })@RequestBody JSONObject jsonParam) {
        try {
            Integer userId = jsonParam.getInteger("userId");
            if (userId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "userId"));
            }

            UserEntity user = userService.getUser(jsonParam);
            return ResponseWrapper.succeed(user);
        }catch (ApiException e){
            log.error(String.format("[前端]获取会员信息失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[前端]获取会员信息失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @CurrentManager
    @RequestMapping(value = "/findList", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[后台]查询会员列表", response = UserVo.class)
    public ResponseWrapper findList(
            @ApiJsonObject(name = "userFindListParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "page", value = "页数", type = "int", required = false),
                    @ApiJsonProperty(key = "pageSize", value = "每页条数", type = "int", required = false),
                    @ApiJsonProperty(key = "mobile", value = "手机号筛选", required = false),
                    @ApiJsonProperty(key = "startTime", value = "注册时间筛选-开始(yyyy-mm-dd)", required = false),
                    @ApiJsonProperty(key = "endTime", value = "注册时间筛选-结束(yyyy-mm-dd)", required = false),
                    @ApiJsonProperty(key = "userLevel", value = "会员等级筛选", type = "int", required = false),
                    @ApiJsonProperty(key = "startAmount", value = "资金区间筛选-开始", type = "int", required = false),
                    @ApiJsonProperty(key = "endAmount", value = "资金区间筛选-结束", type = "int", required = false),
                    @ApiJsonProperty(key = "startTotalAmount", value = "总储值账户资金区间筛选-开始", type = "int", required = false),
                    @ApiJsonProperty(key = "endTotalAmount", value = "总储值账户资金区间筛选-结束", type = "int", required = false)
            })@RequestBody JSONObject jsonParam) {
        try {
            PageInfo<UserVo> list = userService.findList(jsonParam);
            return ResponseWrapper.succeed(list);
        }catch (ApiException e){
            log.error(String.format("[后台]查询会员列表失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]查询会员列表失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @CurrentManager
    @RequestMapping(value = "/findUser", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[后台]获取会员信息", response = UserEntity.class)
    public ResponseWrapper findUser(
            @ApiJsonObject(name = "userFindUserParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "userId", value = "会员id", type = "int")
            }) @RequestBody JSONObject jsonParam) {
        try {
            Integer userId = jsonParam.getInteger("userId");
            if (userId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "userId"));
            }
            UserEntity user = userService.findUser(jsonParam);
            return ResponseWrapper.succeed(user);
        }catch (ApiException e){
            log.error(String.format("[后台]获取会员信息失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]获取会员信息失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @CurrentManager
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[后台]修改会员信息", response = String.class)
    public ResponseWrapper updateUser(
            @ApiJsonObject(name = "userUpdateUserParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "userId", value = "会员id", type = "int"),
                    @ApiJsonProperty(key = "channelId", value = "渠道id", type = "int"),
                    @ApiJsonProperty(key = "levelId", value = "会员等级id", type = "int")
            }) @RequestBody JSONObject jsonParam) {
        try {
            Integer userId = jsonParam.getInteger("userId");
            if (userId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "userId"));
            }
            Integer channelId = jsonParam.getInteger("channelId");
            if (channelId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "channelId"));
            }
            Integer levelId = jsonParam.getInteger("levelId");
            if (levelId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "levelId"));
            }
            userService.updateUser(jsonParam);
            return ResponseWrapper.succeed("修改成功");
        }catch (ApiException e){
            log.error(String.format("[后台]修改会员信息失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]修改会员信息失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @CurrentManager
    @RequestMapping(value = "/exportModel", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[后台]会员导入模版下载", response = String.class)
    public ResponseWrapper exportModel(
            @ApiJsonObject(name = "userExportModelParams", value = {
                    @ApiJsonProperty(key = "token", value = "token值"),
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int")
            }) @RequestBody JSONObject jsonParam) {
        try {
            String url = userService.exportModel(jsonParam);
            return ResponseWrapper.succeed(url);
        }catch (ApiException e){
            log.error(String.format("[后台]会员导入模版下载失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]会员导入模版下载失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @RequestMapping(value = "/importUser", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[后台]会员导入", response = UserEntity.class)
    public ResponseWrapper importUser(@RequestParam(value = "token") String token, @RequestParam(value = "shopId") Integer shopId, @RequestParam(value = "file") MultipartFile file) {
        try {
            TokenEntity tokenEntity = tokenManager.getToken(token);
            Integer managerId = tokenEntity.getUserId();
            if (managerId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW100);
            }

            List<UserVo> list = userService.importUser(managerId, shopId, file);
            return ResponseWrapper.succeed(list);
        }catch (ApiException e){
            log.error(String.format("[后台]会员导入失败，shopId:%s, 错误信息:%s", shopId, e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[后台]会员导入失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @RequestMapping(value="/decrypt", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]解密", response = String.class)
    public ResponseWrapper decrypt(
            @ApiJsonObject(name = "userDecryptParams", value = {
                    @ApiJsonProperty(key = "iv", value = "iv"),
                    @ApiJsonProperty(key = "sessionKey", value = "sessionKey"),
                    @ApiJsonProperty(key = "encryptedData", value = "encryptedData")
            }) @RequestBody JSONObject jsonParam) {
        try {
            String iv = jsonParam.getString("iv");
            String sessionKey = jsonParam.getString("sessionKey");
            String encryptedData = jsonParam.getString("encryptedData");
            log.info(String.format("decrypt 参数： iv: %s, sessionKey: %s, encryptedData: %s", iv, sessionKey, encryptedData));

            sessionKey = URLDecoder.decode(sessionKey, StandardCharsets.UTF_8.name());
            iv = URLDecoder.decode(iv, StandardCharsets.UTF_8.name());
            encryptedData = URLDecoder.decode(encryptedData, StandardCharsets.UTF_8.name());
            String plainText = AES.wxDecrypt(encryptedData, sessionKey, iv);
            log.info(String.format("解密数据：%s", plainText));
            //修改用户基本信息
            userService.updateBaseInfo(plainText);
            return ResponseWrapper.succeed(JSONObject.parseObject(plainText));
        } catch (Exception e) {
            log.error(String.format("[前端小程序]解密失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @RequestMapping(value="/getByMobile", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]手机号授权注册登录", response = UserEntity.class)
    public ResponseWrapper getByMobile(
            @ApiJsonObject(name = "userGetByMobileParams", value = {
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "mobile", value = "手机号"),
                    @ApiJsonProperty(key = "openid", value = "openid"),
                    @ApiJsonProperty(key = "unionid", value = "unionid", required = false),
                    @ApiJsonProperty(key = "parentId", value = "分销人id", required = false)
            })@RequestBody JSONObject jsonParam) {
        try {
            String mobile = jsonParam.getString("mobile");
            if (StringUtils.isNullStr(mobile)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "mobile"));
            }
            String openid = jsonParam.getString("openid");
            if (StringUtils.isNullStr(openid)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "openid"));
            }
//            String unionid = jsonParam.getString("unionid");
//            if (StringUtils.isNullStr(unionid)) {
//                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "unionid"));
//            }
            UserVo user = userService.getByMobile(jsonParam);
            return ResponseWrapper.succeed(user);
        } catch (ApiException e) {
            log.error(String.format("[前端小程序]手机号授权注册登录失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端小程序]手机号授权注册登录失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @RequestMapping(value="/getWxOpenId", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]请求微信接口获取openId", response = UserVo.class)
    public ResponseWrapper getWxOpenId(
            @ApiJsonObject(name = "userGetWxOpenIdParams", value = {
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "code", value = "code"),
                    @ApiJsonProperty(key = "parentId", value = "分销人id", required = false)
            }) @RequestBody JSONObject jsonParam) {
//        jsonParam.put("shopId",1);
    	try {
    		String jsCode = jsonParam.getString("code");
    		if (jsCode == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "code"));
            }
            UserVo user = userService.getOpenId(jsonParam);
			return ResponseWrapper.succeed(user);
		} catch (ApiException e) {
            log.error(String.format("[前端小程序]请求微信接口获取openId失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端小程序]请求微信接口获取openId失败"), e);
			return ResponseWrapper.failed(ErrorCodeEnum.FL500);
		}
    }

    @CurrentShop
    @RequestMapping(value="/getOpenId", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]请求微信接口获取openId", response = WechatOpenIdExistsVO.class)
    public ResponseWrapper getWxOpenId(@ApiParam(value = "用户基本信息") @RequestBody  WechatCodeQueryDTO wechatCodeQueryDTO) {
        try {
            String jsCode = wechatCodeQueryDTO.getCode();
            if (jsCode == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "code"));
            }
            return ResponseWrapper.succeed(userQueryService.getOpenIdExistsByCode(wechatCodeQueryDTO));
        } catch (ApiException e) {
            log.error(String.format("[前端小程序]请求微信接口获取openId失败，参数:%s, 错误信息:%s",
                    JSONObject.toJSONString(wechatCodeQueryDTO), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端小程序]请求微信接口获取openId失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @RequestMapping(value="/registerByOpenId", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]请求微信接口获取openId", response = UserVo.class)
    public ResponseWrapper getWxOpenId(@ApiParam(value = "用户基本信息") @RequestBody WechatRegisterDTO wechatCodeQueryDTO) {
        try {
            return ResponseWrapper.succeed(userOperatorService.WechatRegister(wechatCodeQueryDTO));
        } catch (ApiException e) {
            log.error(String.format("[前端小程序]根据openid注册用户失败，参数:%s, 错误信息:%s",
                    JSONObject.toJSONString(wechatCodeQueryDTO), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端小程序]根据openid注册用户失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @RequestMapping(value="/getUserInfo", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]获取用户信息", response = UserVo.class)
    public ResponseWrapper getUserInfo(
            @ApiJsonObject(name = "userGetUserInfoParams", value = {
                    @ApiJsonProperty(key = "userId", value = "用户id", type = "int")
            }) @RequestBody JSONObject jsonParam) {
        try {
            Integer userId = jsonParam.getInteger("userId");
            if(userId == null){
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "userId"));
            }
            UserVo user = userService.getUserInfo(userId);
            return ResponseWrapper.succeed(user);
        } catch (ApiException e) {
            log.error(String.format("[前端小程序]获取用户信息失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端小程序]获取用户信息失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @RequestMapping(value="/getSignature", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]领取卡券生成签名", response = Map.class)
    public ResponseWrapper getSignature(
            @ApiJsonObject(name = "userGetSignatureParams", value = {
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "cardId", value = "cardId")
            }) @RequestBody JSONObject jsonParam) {
    	try {
    		String cardId = jsonParam.getString("cardId");
    		if (cardId == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "cardId"));
            }
			return ResponseWrapper.succeed(userService.getSignature(jsonParam));
		} catch (ApiException e) {
            log.error(String.format("[前端小程序]领取卡券生成签名失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端小程序]领取卡券生成签名失败"), e);
			return ResponseWrapper.failed(ErrorCodeEnum.FL500);
		}
    }
    
    @CurrentShop
    @RequestMapping(value = "/saveCardNum", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]保存会员卡号", response = ManagerEntity.class)
    public ResponseWrapper saveCardNum(
            @ApiJsonObject(name = "userSaveCardNumParams", value = {
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "mobile", value = "手机号"),
                    @ApiJsonProperty(key = "code", value = "code")
            }) @RequestBody JSONObject jsonParam) {
        try {
            String mobile = jsonParam.getString("mobile");
            String code = jsonParam.getString("code");
            if (mobile == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "手机号"));
            }
            if (code == null) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "code"));
            }

            UserEntity user = userService.saveCardNum(jsonParam);
            return ResponseWrapper.succeed(user);
        }catch (ApiException e){
            log.error(String.format("[前端]保存会员卡号，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        }catch (Exception e){
            log.error(String.format("[前端]保存会员卡号"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @RequestMapping(value="/saveOpenid", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]保存unionid", response = boolean.class)
    public ResponseWrapper saveUnionid(
            @ApiJsonObject(name = "userSaveUnionidParams", value = {
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "openid", value = "openid"),
                    @ApiJsonProperty(key = "unionid", value = "unionid")
            })@RequestBody JSONObject jsonParam) {
        try {
            String openid = jsonParam.getString("openid");
            if (StringUtils.isNullStr(openid)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "openid"));
            }
            String unionid = jsonParam.getString("unionid");
            if (StringUtils.isNullStr(unionid)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "unionid"));
            }
            userService.saveOpenid(jsonParam);
            return ResponseWrapper.succeed(true);
        } catch (ApiException e) {
            log.error(String.format("[前端小程序]保存unionid失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端小程序]保存unionid失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @RequestMapping(value="/saveFormid", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]保存formid", response = boolean.class)
    public ResponseWrapper saveFormid(
            @ApiJsonObject(name = "userSaveFormidParams", value = {
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "openid", value = "openid"),
                    @ApiJsonProperty(key = "formid", value = "formid")
            })@RequestBody JSONObject jsonParam) {
        try {
            String openid = jsonParam.getString("openid");
            if (StringUtils.isNullStr(openid)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "openid"));
            }
            String formid = jsonParam.getString("formid");
            if (StringUtils.isNullStr(formid)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "formid"));
            }
            userService.saveFormid(jsonParam);
            return ResponseWrapper.succeed(true);
        } catch (ApiException e) {
            log.error(String.format("[前端小程序]保存formid失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端小程序]保存formid失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }

    @CurrentShop
    @RequestMapping(value="/getUnlimited", method = RequestMethod.POST)
    @ApiOperation(tags = "会员", httpMethod = "POST", value = "[前端小程序]获取小程序码", response = String.class)
    public ResponseWrapper getUnlimited(
            @ApiJsonObject(name = "userGetUnlimitedParams", value = {
                    @ApiJsonProperty(key = "shopId", value = "商铺id", type = "int"),
                    @ApiJsonProperty(key = "userId", value = "用户id")
            })@RequestBody JSONObject jsonParam) {
        try {
            String userId = jsonParam.getString("userId");
            if (StringUtils.isNullStr(userId)) {
                return ResponseWrapper.failed(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "userId"));
            }
            String url = userService.getUnlimited(jsonParam);
            log.info(String.format("getUnlimited userId: %s, url: %s", userId, url));
            return ResponseWrapper.succeed(url);
        } catch (ApiException e) {
            log.error(String.format("[前端小程序]获取小程序码失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("[前端小程序]获取小程序码失败"), e);
            return ResponseWrapper.failed(ErrorCodeEnum.FL500);
        }
    }
}
